package com.defysoft.waukids.album;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseActivity;
import com.defysoft.waukids.Data_Sharedpreferences;
import com.defysoft.waukids.PublicSharedpreferences;
import com.defysoft.waukids.R;
import com.defysoft.waukids.Sqlite_Connect;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.polites.android.GestureImageView;

public class AlbumDetailPhoto extends BaseActivity  {
	String photo;
	String photoname;
	GestureImageView gv;
	ImageLoader imageLoader;
	ImageView downbtn;
	DisplayImageOptions options;
	Bitmap bitmap;
	public Sqlite_Connect sqlite_Connect;
	PublicSharedpreferences psf;
	public Data_Sharedpreferences.SF_Member member;
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.album_detail_photo_a);
		sqlite_Connect = new Sqlite_Connect(this);
		psf = new PublicSharedpreferences(this);
		psf.setMembersp();
		member = psf.getMembersp();
		photo = getIntent().getStringExtra("photo");
		photoname = getIntent().getStringExtra("photoname");
		gv = (GestureImageView) findViewById(R.id.ALBUM_DETAIL_PHOTO_IV);
		downbtn = (ImageView) findViewById(R.id.ALBUM_DETAIL_PHOTO_DOWN);
		downbtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startNetwork(1);
				startDIal();

			}
		});
		// 이미지 세팅.
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				this).threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				.discCacheFileNameGenerator(new Md5FileNameGenerator())
				.tasksProcessingOrder(QueueProcessingType.LIFO)
				.writeDebugLogs() // Remove for release app
				.build();
		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(config);
		imageLoader = ImageLoader.getInstance();

		options = new DisplayImageOptions.Builder().cacheInMemory(true)
				.imageScaleType(ImageScaleType.EXACTLY).cacheOnDisc(true)
				.considerExifParams(true).build();

		imageLoader.displayImage(photo, gv, options, null);

		registerReceiver(mToastMessageReceiver, new IntentFilter(
				"com.defysoft.waukids.TOAST_MESSAGE"));
	}

	@Override
	protected void handlingMessage(Message _message) {
		// TODO Auto-generated method stub
		super.handlingMessage(_message);
		switch (_message.what) {
		case 1:
			endDIal();
			Toast.makeText(AlbumDetailPhoto.this, "waukidsphoto 폴더에 저장이 완료되었습니다.",Toast.LENGTH_LONG).show();	
			sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+"/mnt/sdcard/waukidsphoto/"+photoname+".JPEG")));
			break;

		case CATCH_EXCEPTION:
			endDIal();
			sqlite_Connect.insert_Err_Log((String)_message.obj,android.os.Build.VERSION.SDK_INT,"AlbumDetailPhoto", member.Email);
			break;
		}
		
		
		/*sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
				 Uri.parse("file://" + Environment.getExternalStorageDirectory())));*/
	}

	@Override
	public void startThread(int choice) {
		// TODO Auto-generated method stub
		super.startThread(choice);
		firstThread = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					bitmap = GetImageFromURL(photo);

					String str = Environment.getExternalStorageState();
					if (str.equals(Environment.MEDIA_MOUNTED)) {

						String dirPath = "mnt/sdcard/waukidsphoto";
						File file = new File(dirPath);
						if (!file.exists()) // 원하는 경로에 폴더가 있는지 확인
							file.mkdirs();
					} else
						Toast.makeText(AlbumDetailPhoto.this, "SD Card 인식 실패",
								Toast.LENGTH_SHORT).show();

					File file = new File("filepath");
					final FileOutputStream filestream = new FileOutputStream(
							"/mnt/sdcard/waukidsphoto/"+photoname+".JPEG");
					bitmap.compress(CompressFormat.JPEG, 90, filestream);

				} catch (Exception e) {
					onNetworkCallback(CATCH_EXCEPTION, e.toString()+" where startThread() ");
				}
				onNetworkCallback(1, "");
			}
		});
		firstThread.start();
	}

	
	
	private Bitmap GetImageFromURL(String strImageURL) {
		Bitmap imgBitmap = null;

		try {
			URL url = new URL(strImageURL);
			URLConnection conn = url.openConnection();
			conn.connect();

			int nSize = conn.getContentLength();
			BufferedInputStream bis = new BufferedInputStream(
					conn.getInputStream(), nSize);
			imgBitmap = BitmapFactory.decodeStream(bis);

			bis.close();
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString()+" where GetImageFromURL(String strImageURL)");
		}
		return imgBitmap;
	}
	
	private final BroadcastReceiver mToastMessageReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			LinearLayout layout = (LinearLayout)getLayoutInflater().inflate(R.layout.toast_layout, null);
			TextView toast_tv = (TextView)layout.findViewById(R.id.TOAST_LAYOUT_TV);
			Toast toast = new Toast(AlbumDetailPhoto.this);
			toast.setView(layout);
			toast_tv.setText(intent.getStringExtra("PUSH_NAME")+" : "+intent.getStringExtra("PUSH_SUB"));
			toast.setDuration(Toast.LENGTH_LONG);
			toast.show();
		}
	};
}
